package com.server.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.server.common.base.PathManager;
import com.server.date.DateType;
import com.server.date.DateUtil;
import com.server.service.ICommonDataService;
import com.server.service.ICourseStudyService;
import com.server.web.DataVector;
import com.server.web.RequestInput;

@Service("CourseStudyService")
public class CourseStudyService implements ICourseStudyService {
	
	/*
	 * 记录一定时间内的课程点击量，定时写入到数据库
	 */
	private Map<Integer, Integer> tempClickCount = new HashMap<Integer, Integer>();
	private ReadWriteLock lock = new ReentrantReadWriteLock(false);
	
	private final String tableName = "education.course";
	private final String viewName = "education.v_course_class";
	private final String viewName_file = "education.v_course_file";

	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private ICommonDataService commonDataService;
	
	@Override
	public DataVector<Map<String, Object>> getList(String whereStr, 
			String sortStr, RequestInput requestInput){
		return commonDataService.getListData(viewName, whereStr, sortStr, requestInput);
	}
	@Override
	public Map<String, Object> getForm(HttpServletRequest request,Integer id){
		Map<String, Object> map = new HashMap<String, Object>();
		String sql = "select * from %s where id=%s";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(String.format(sql, viewName_file,id));
		
		StringBuffer serverBuffer = new StringBuffer();
		String serverName = request.getServerName();
		int serverPort = request.getServerPort();
		serverBuffer.append("http://").append(serverName)
		.append(":").append(serverPort).append("/")
		.append(PathManager.FILE_MAPPING);
		
		if (list.size() > 0) {
			map = list.get(0);
			Object path1Obj = map.get("filePath1");
			Object uuid1Obj = map.get("uuid1");
			Object path2Obj = map.get("filePath2");
			Object uuid2Obj = map.get("uuid2");
			Object path3Obj = map.get("filePath3");
			Object uuid3Obj = map.get("uuid3");
			if (path1Obj != null && uuid1Obj != null) {
				map.put("sourceUrl", serverBuffer.toString()+path1Obj.toString()+"/"+uuid1Obj.toString());
			}
			if (path2Obj != null && uuid2Obj != null) {
				map.put("pptUrl", path2Obj.toString()+"/"+uuid2Obj.toString()+".pdf");
			}
			if (path3Obj != null && uuid3Obj != null) {
				map.put("imgUrl", serverBuffer.toString()+path3Obj.toString()+"/"+uuid3Obj.toString());
			}
		}else {
			return new HashMap<String, Object>();
		}
		return map;
	}
	/**
	 * 获得课程目录树对应附件
	 * @param id
	 * @return
	 * @author ServerZhang
	 * @date 2016年8月9日
	 */
	@Override
	public List<Map<String, Object>> getCatalog(Integer id){
		List<Map<String, Object>> returnList = new ArrayList<Map<String,Object>>();
		String sql = "select * from education.v_file_list_course where courseId=%s order by pid,id";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(String.format(sql, id));
		Iterator<Map<String, Object>> iterator = list.iterator();
		Map<Object, Integer> chapterMap = new HashMap<Object, Integer>();
		Integer chapter = 1;
		Integer part = 1;
		Integer lastP = 0;
		while(iterator.hasNext()){
			Map<String, Object> next = iterator.next();
			Object pidObj = next.get("pid");//父级
			Object cidObj = next.get("cid");
			Object nameObj = next.get("catalogName");
			Object idObj = next.get("id");//附件id
			String name = nameObj == null ? "" : nameObj.toString();
			if (cidObj == null) {
				continue;
			}
			if (pidObj == null || "0".equals(pidObj.toString())
					|| "".equals(pidObj.toString())) {
				chapterMap.put(cidObj, chapter++);
			}else {
				int pid = Integer.parseInt(pidObj.toString());
				if (pid == lastP) {//同父
					
				}else{//不同父
					lastP = pid;
					part = 1;
				}
				name = chapterMap.get(pidObj)+"."+part+++" "+name;
				next.put("catalogName", name);
				returnList.add(next);
			}
		}
		return returnList;
	}
	 /**
	 * 初始化课程点击量
	 * @author ServerZhang
	 * @date 2016年8月9日
	 */
	@Override
	public void loadClickCount(){
		String sql = "select id,clickNum from education.course where valid=1 and id is not null and clickNum is not null";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
		Iterator<Map<String, Object>> iterator = list.iterator();
		while(iterator.hasNext()){
			Map<String, Object> next = iterator.next();
			this.tempClickCount.put(Integer.parseInt(next.get("id").toString()), Integer.parseInt(next.get("clickNum").toString()));
		}
	}
	 /**
	 * 课程被点击
	 * @param id
	 * @author ServerZhang
	 * @date 2016年8月9日
	 */
	@Override
	public void click(Integer id){
		lock.writeLock().lock();
		lock.readLock().lock();
		Integer count = this.tempClickCount.get(id);
		if (count == null) {
			this.tempClickCount.put(id, 1);
		}else {
			this.tempClickCount.put(id, count+1);
		}
		lock.readLock().unlock();
		lock.writeLock().unlock();
	}
	 /**
	 * 将课程点击量回写到数据库中
	 * @author ServerZhang
	 * @date 2016年8月9日
	 */
	@Override
	public void clickRecord(){
		String sql = "update education.course set clickNum=%s where id=%s";
		Map<Integer, Integer> countMap = this.tempClickCount;
		Set<Integer> keySet = countMap.keySet();
		String[] sqls = new String[countMap.size()];
		int index = 0;
		for(Integer key : keySet){
			sqls[index++] = String.format(sql, countMap.get(key), key);
		}
		jdbcTemplate.batchUpdate(sqls);
	}
	@Override
	public Boolean studyProcess(Map<String, Object> inputMap, String nickname) {
		Object courseObj = inputMap.get("courseId");
		Object fileObj = inputMap.get("fileId");
		Object timeObj = inputMap.get("totalTime");
		if (courseObj == null || fileObj == null 
				|| StringUtils.isEmpty(nickname) || timeObj == null) {
			return false;
		}
		String whereStr = String.format("courseId='%s' and fileId='%s' and creater='%s'", courseObj.toString(),fileObj.toString(),nickname);
		String sql = "select count(id) from education.study where %s";
		Integer count = jdbcTemplate.queryForObject(String.format(sql, whereStr), Integer.class);
		Boolean isSuccess = false;
		if (count == null || count <= 0) {
			isSuccess = commonDataService.add(nickname, "education.study", inputMap);
		}else {
			String updateStr = "update education.study set totalTime='%s' where %s";
			int update = jdbcTemplate.update(String.format(updateStr, timeObj.toString(),whereStr));
			isSuccess = update > 0;
		}
		return isSuccess;
	}
	/**
	 * 查询学习记录  如果该章节记录不存在返回true进行记录
	 * 
	 * @param whereMap
	 * @return
	 * @author xiaoxiaoping
	 * @date 2016年8月10日
	 */
	@Override
	public Map<String, Object> selectStudy(Map<String, Object> whereMap) {
		if(whereMap.size()<0 || whereMap == null){
			return null;
		}
		StringBuffer whereBuffer = new StringBuffer();
		
		Set<String> keySet = whereMap.keySet();
		for(String key : keySet){
			if(whereBuffer.length()>0){
				whereBuffer.append(" and ").append(" ").append(key);
				whereBuffer.append("='").append(whereMap.get(key)).append("'");
			}else{
				whereBuffer.append(" ").append(key);
				whereBuffer.append("='").append(whereMap.get(key)).append("'");
			}
			
		}
		StringBuffer sqlBuffer = new StringBuffer();
		sqlBuffer.append("select * from education.study where");
		sqlBuffer.append(whereBuffer);
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sqlBuffer.toString());
		if(list.size()>0){
			return  list.get(0);
		}else{
			return null;
		}
	}
	@Override
	public Boolean updateProcess(Map<String, Object> whereMap,
			String currentTime) {
		if(whereMap.size()<0 || whereMap == null){
			return false;
		}
		//Integer time =  Integer.parseInt(currentTime);
		StringBuffer setBuffer = new StringBuffer();
		setBuffer.append("currentTime='").append(currentTime).append("'");
		StringBuffer whereBuffer = new StringBuffer();
		
		Set<String> keySet = whereMap.keySet();
		for(String key : keySet){
			if(whereBuffer.length()>0){
				whereBuffer.append(" and ").append(" ").append(key);
				whereBuffer.append("='").append(whereMap.get(key)).append("'");
			}else{
				whereBuffer.append(" ").append(key);
				whereBuffer.append("='").append(whereMap.get(key)).append("'");
			}
		}
		StringBuffer sqlBuffer = new StringBuffer();
		sqlBuffer.append("update education.study set ");
		sqlBuffer.append(setBuffer).append(" where").append(whereBuffer);
		try {
			int id = jdbcTemplate.update(sqlBuffer.toString()); 
			if (id<0) {
				return false;
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	@Override
	public Boolean updateEndProcess(Map<String, Object> whereMap) {
		if(whereMap.size()<0 || whereMap == null){
			return false;
		}
		StringBuffer setBuffer = new StringBuffer();
		String dateStr = DateUtil.getDateStr(new Date(),DateType.YYYY_MM_DD_HH_mm_ss_SSS);
		setBuffer.append("endTime='").append(dateStr).append("'");
		StringBuffer whereBuffer = new StringBuffer();
		
		Set<String> keySet = whereMap.keySet();
		for(String key : keySet){
			if(whereBuffer.length()>0){
				whereBuffer.append(" and ").append(" ").append(key);
				whereBuffer.append("='").append(whereMap.get(key)).append("'");
			}else{
				whereBuffer.append(" ").append(key);
				whereBuffer.append("='").append(whereMap.get(key)).append("'");
			}
			
		}
		StringBuffer sqlBuffer = new StringBuffer();
		sqlBuffer.append("update education.study set ");
		sqlBuffer.append(setBuffer).append(" where").append(whereBuffer);
		try {
			int id = jdbcTemplate.update(sqlBuffer.toString()); 
			if (id<0) {
				return false;
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	@Override
	public int countProcess(Integer id,String nickname) {
		String sql = "select count(*) from education.course_list where pid>0 and courseId=%d";
		String sql1 = "select count(*) from education.study where courseId=%d and creater='%s' and endTime!=''";
		Integer countTotal = jdbcTemplate.queryForObject(String.format(sql, id), Integer.class);
		Integer count = jdbcTemplate.queryForObject(String.format(sql1, id,nickname), Integer.class);
		if(countTotal==0){
			return 0;
		}
		double countTotal_temp = countTotal;
		double count_temp = count;
		float Total = (float) countTotal_temp;
		float base = (float) count_temp;
		float process = base/Total; 
		int val = (int) (process*100);
		return val;
	}
	@Override
	public Boolean addNotes(Map<String, Object> inputMap, String operator) {
		Boolean isSuccess = commonDataService.add(operator, "education.notes", inputMap);
		return isSuccess;
	}
	@Override
	public Map<String, Object> getNotes(Map<String, Object> whereMap) {
		if(whereMap.size()<0 || whereMap == null){
			return null;
		}
		StringBuffer whereBuffer = new StringBuffer();
		
		Set<String> keySet = whereMap.keySet();
		for(String key : keySet){
			whereBuffer.append(" ").append(key);
			whereBuffer.append("='").append(whereMap.get(key)).append("' and ");
		}
		whereBuffer.append("1=1");
		StringBuffer sqlBuffer = new StringBuffer();
		sqlBuffer.append("select * from education.notes where");
		sqlBuffer.append(whereBuffer);
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sqlBuffer.toString());
		if(list.size()>0){
			return  list.get(0);
		}else{
			return null;
		}
	}
	@Override
	public Boolean updateNotes(Map<String, Object> whereMap, String content) {
		if(whereMap.size()<0 || whereMap == null){
			return false;
		}
		StringBuffer setBuffer = new StringBuffer();
		setBuffer.append("content='").append(content);
		String dateStr = DateUtil.getDateStr(new Date(),DateType.YYYY_MM_DD_HH_mm_ss_SSS);
		setBuffer.append("',updateTime='").append(dateStr).append("'");
		StringBuffer whereBuffer = new StringBuffer();
		
		Set<String> keySet = whereMap.keySet();
		for(String key : keySet){
			whereBuffer.append(" ").append(key);
			whereBuffer.append("='").append(whereMap.get(key)).append("' and ");
		}
		whereBuffer.append("1=1");
		StringBuffer sqlBuffer = new StringBuffer();
		sqlBuffer.append("update education.notes set ");
		sqlBuffer.append(setBuffer).append(" where").append(whereBuffer);
		try {
			int id = jdbcTemplate.update(sqlBuffer.toString()); 
			if (id<0) {
				return false;
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	@Override
	public Map<String, Object> getCon(Integer id) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		String sql = "select * from education.course_res where id=%d";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(String.format(sql, id));
		if(list.size()>0){
			returnMap = list.get(0);
		}
		return returnMap;
	}
	@Override
	public int countProcess2(Integer id, String nickname) {
		String sql="select * from education.study where courseId=%d and creater='%s'";
		List<Map<String, Object>> list=jdbcTemplate.queryForList(String.format(sql, id,nickname));
		if(list.size()>0){
			Map<String, Object> map = list.get(0);
			
			if(map.get("endTime")==null){
				double current = 0.0;
				double total = 0.0;
				double progress = 0.0;
				Object currentObj = map.get("currentTime");
				Object totalObj = map.get("totalTime");
				if (currentObj != null && totalObj != null) {
					current = Double.parseDouble(currentObj.toString());
					total = Double.parseDouble(totalObj.toString());
					if (total == 0.0) {
						return 0;
					}
					progress = current / total;
					return (int)(progress * 100);
				}else {
					return 0;
				}
				
				/*int total=0;
				int current=0;
				float ftotal=0;
				float fcurrent=0;
				if(map.get("totalTime")==null){
					return 0;
				}else{
					total = (int) map.get("totalTime");
					ftotal = (float) total;
					
				}
				if(map.get("currentTime")==null){
					return 0;
				}else{
					current = (int) map.get("currentTime");
					fcurrent = (float) current;
					
				}
				if((int) ftotal == 0){
					return 0;
				}
				return (int) (fcurrent/ftotal*100);*/
			}else{
				return 100;
			}
		}else {
			return 0;
		}
	}
	@Override
	public Map<String, Object> getVidoPptRelation(Integer courseId) {
		String sql="select * from education.course where id=%d";
		Map<String, Object> map=jdbcTemplate.queryForMap(String.format(sql, courseId));
		Map<String, Object> relMap = new HashMap<String,Object>();
		String vidoPptRelStr = "";
		String contentStr = "";
		String contentPptRel = "";
		if ( map!=null ) {
			if (map.get("pdfPptRel")!=null) {
				vidoPptRelStr = map.get("pdfPptRel").toString();
			}
			if (map.get("contentStr")!=null) {
				contentStr = map.get("contentStr").toString();
			}
			if (map.get("contentPptRel")!=null) {
				contentPptRel = map.get("contentPptRel").toString();
			}
		}
		if (!StringUtils.isEmpty(vidoPptRelStr)) {
			String []rel = vidoPptRelStr.split(",");
			List<Integer> list = new ArrayList<Integer>();
			for (int i = 0; i < rel.length; i++) {
				list.add(Integer.parseInt(rel[i]));
			}
			relMap.put("vidoppt", list);
		}
		if (!StringUtils.isEmpty(contentStr)) {
			contentStr = contentStr.substring(0, contentStr.length()-1);
			String []contents = contentStr.split("&");
			List<String> list = new ArrayList<String>();
			for (int i = 0; i < contents.length; i++) {
				String string = contents[i];
				list.add(string);
			}
			relMap.put("content", list);
		}
		if (!StringUtils.isEmpty(contentPptRel)) {
			contentPptRel = contentPptRel.substring(0, contentPptRel.length()-1);
			String []rel = contentPptRel.split(",");
			List<Integer> list = new ArrayList<Integer>();
			for (int i = 0; i < rel.length; i++) {
				list.add(Integer.parseInt(rel[i]));
			}
			relMap.put("contentppt", list);
		}
		return relMap;
	}
	
}
